package com.klikmee.sms.core.base.communicator.starion;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.communicator.DeliveryReport;
import com.klikmee.sms.core.base.communicator.DeliveryReport2MessageResolver;
import com.klikmee.sms.core.base.dao.BulkMessageDAO;
import com.klikmee.sms.core.base.exceptions.DeliveryReportNotResolvedException;
import com.klikmee.sms.core.commons.exceptions.ErrorInfo;
import com.klikmee.sms.core.model.BulkMessage;

/**
 * Resolves bulk delivery report from Starion to bulk messages. Uses provider's
 * message id to resolve message.
 * 
 * @author makcro
 * 
 */
public class StarionBulkDeliveryReport2MessageResolverImpl implements DeliveryReport2MessageResolver<BulkMessage> {

	/**
	 * Logger instance
	 */
	private Logger			logger	= Logger.getLogger( StarionBulkDeliveryReport2MessageResolverImpl.class );

	/**
	 * Dao used to access bulk message
	 */
	private BulkMessageDAO	bulkMessageDAO;

	@Override
	public BulkMessage resolve(DeliveryReport deliveryReport) throws DeliveryReportNotResolvedException {
		// try to find bulk message by providers message id and name
		BulkMessage sentMessage = this.bulkMessageDAO.findByProvidersIdAndProviderName( deliveryReport.getProvidersMessageId(), deliveryReport.getProvider().getName() );
		// if outgoing message could not be found, throw an exception
		if (sentMessage == null) {
			DeliveryReportNotResolvedException exception = new DeliveryReportNotResolvedException( "Could not resolve bulk delivery report for starion provider" );
			ErrorInfo errorInfo = exception.addInfo();
			errorInfo.getParameters().put( "MessageId", deliveryReport.getMessageId() );
			errorInfo.getParameters().put( "Provider", deliveryReport.getProvider().getName() );
			throw exception;
		}
		logger.info( MessageFormat.format( "Resolved delivery report to BulkMessage[{0}]", sentMessage.getId() ) );
		return sentMessage;
		
	}

	public BulkMessageDAO getBulkMessageDAO() {
		return bulkMessageDAO;
	}

	public void setBulkMessageDAO(BulkMessageDAO bulkMessageDAO) {
		this.bulkMessageDAO = bulkMessageDAO;
	}

}
